<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="150"
    >
      <el-form-item label="审批状态" prop="approvalState">
        <el-select
          clearable
          v-model="formData.approvalState"
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BID_APPROVAL_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.approvalState === 30" label="保证金扣款(元)" prop="marginDeduct">
        <el-input :maxlength="10" v-model="formData.marginDeduct" placeholder="请输入保证金扣款" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.remark" :maxlength="100" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item class="text-red-500">
        温馨提示：审批通过之后，审批的结果会以短信的方式提醒客户。
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { validateTransAmount } from '@/utils/validatorUtil'
import * as subjectManage from '@/api/subjectManage'
import * as Utils from '@/utils/dict'

const { DICT_TYPE, getIntDictOptions } = reactive(Utils)
const emit = defineEmits(['success'])
const formRef = ref()
const { t } = useI18n()
const message = useMessage()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formData: Record<string, any> = ref({
  approvalState: undefined,
  marginDeduct: 0,
  remark: undefined
})
const rowId = ref()

const formRules = reactive({
  approvalState: [{ required: true, message: '审批状态不能为空', trigger: 'change' }],
  marginDeduct: [{ validator: validateTransAmount, trigger: 'blur' }]
})

const open = async (id) => {
  resetFn()
  dialogVisible.value = true
  dialogTitle.value = '审批'
  rowId.value = id
}

const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    formLoading.value = true
    await subjectManage.approveFn({ id: rowId.value, ...formData.value })
    message.success(t('common.operateSuccess'))
    dialogVisible.value = false
    resetFn()
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetFn = () => {
  formData.value = {
    approvalState: undefined,
    marginDeduct: 0,
    remark: undefined
  }
  formRef.value?.resetFields()
}

defineExpose({ open })
</script>
